<template>
  <div class="edit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{title}}</span>
        <el-button @click="$router.go(-1)" style="float: right; padding: 3px 0" type="text">返回</el-button>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="登录账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入手机号或登录账号" />
        </el-form-item>

        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入登录密码" />
        </el-form-item>

        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="form.birthday" type="date" placeholder="请选择出生日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>

        <el-form-item label="用户头像" prop="avatar">
          <Upload v-model="form.avatar" @clear="clearImageValidate" />
        </el-form-item>

        <el-form-item label="用户简介" prop="introduction">
          <el-input type="textarea" :rows="4" v-model="form.introduction" placeholder="请输入用户简介" />
        </el-form-item>
        <el-form-item label="顾问选择">
          <el-button
            @click="chooseAdvisor(1)"
            type="primary"
            size="mini"
          >{{counselorInfo?'重新':''}}选择</el-button>
          <el-button type="text" v-if="counselorInfo">{{counselorInfo.counselorName}}</el-button>
        </el-form-item>
        <el-form-item label="设置为推广员" prop="userType">
          <el-switch v-model="form.userType" :active-value="2" :inactive-value="1"></el-switch>
        </el-form-item>
        <el-form-item label="推广员">
          <el-button
            @click="chooseAdvisor(2)"
            type="primary"
            size="mini"
          >{{salespersonInfo?'重新':''}}选择</el-button>
          <el-button type="text" v-if="salespersonInfo">{{salespersonInfo.salespersonName}}</el-button>
        </el-form-item>
        <el-form-item label="设备码">
          <div v-for="(item,index) in form.equipments" :key="index">
            <span>{{item.mac}}</span>
            <el-button
              style="margin-left:20px;"
              @click="removeDevice(index,item.id)"
              type="text"
              size="mini"
            >删除</el-button>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">重置</el-button>
        </el-form-item>
      </el-form>

      <el-dialog
        :title="modalTitle"
        :visible.sync="openChooseAdvisor"
        width="1200px"
        append-to-body
      >
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="80px"
        >
          <el-form-item label="姓名" prop="userName">
            <el-input
              v-model="queryParams.userName"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table
          v-loading="loading"
          :data="advisorList"
          highlight-current-row
          @current-change="handleCurrentChange"
          ref="singleTable"
        >
          <el-table-column label="姓名" align="center" prop="nickName" />
          <el-table-column label="手机号" align="center" prop="phonenumber" />
          <el-table-column label="服务客户数量" align="center" prop="serviceNumber" />
          <el-table-column label="添加时间" align="center" prop="createTime" />
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="paginationChange"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="sureChooseAdvisor">确定</el-button>
          <el-button @click="cancelChooseAdvisor">取消</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import Upload from "@/components/Upload";
import { listUser, getUser, addUser, updateUser } from "@/api/system/user";
import { listAdvisor } from "@/api/system/advisor";

export default {
  name: "UserEdit",
  components: {
    Upload
  },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      openChooseAdvisor: false,
      title: "新增用户",
      modalTitle: "选择顾问(点击行即可选择)",
      chooseType: 1, // 1=选择顾问 2= 选择推广员
      counselorInfo: null, // 选择的顾问信息
      salespersonInfo: null, // 选择的推广员信息
      // 总条数
      total: 0,
      // 顾问表格数据
      advisorList: [],
      loading: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: ""
      },
      // 表单参数
      form: {
        userName: "",
        nickName: "",
        phonenumber: "",
        password: "",
        birthday: "",
        avatar: "",
        introduction: "",
        password: "",
        salesperson: "", // 顾问id
        counselor: "", //推广员id
        removeEquipmentIds: []
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "请输入用户昵称", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "请输入手机号或登录账号", trigger: "blur" }
        ],
        phonenumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入登录密码", trigger: "blur" }
        ],
        birthday: [{ required: true, message: "生日不能为空" }],
        email: [
          { required: true, message: "邮箱地址不能为空", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        // avatar: [{ required: true, message: "请上传用户头像" }]
      }
    };
  },
  mounted() {
    this.getEditInfo();
  },
  methods: {
    change(value) {
      this.form.goodsStandard = value;
    },
    clearImageValidate() {
      this.rules.avatar = [];
      this.$refs["form"].clearValidate("avatar");
    },
    paginationChange() {
      if (this.chooseType === 1) {
        this.getAdvisorList();
      } else {
        this.getUserList();
      }
    },
    chooseAdvisor(type) {
      if (type === 2) {
        this.modalTitle = "选择推广员(点击行即可选择)";
        this.getUserList();
      } else {
        this.getAdvisorList();
      }
      this.chooseType = type;
      this.openChooseAdvisor = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.chooseType === 1) {
        this.getAdvisorList();
      } else {
        this.getUserList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleCurrentChange(val) {
      console.log("val", val);
      if (this.chooseType === 1) {
        this.counselorInfo = {
          id: val.id,
          counselorName: val.userName
        };
        this.form.counselor = val.id;
      } else {
        this.salespersonInfo = {
          id: val.userId,
          salespersonName: val.userName
        };
        this.form.salesperson = val.userId;
      }
    },
    sureChooseAdvisor() {
      if (this.chooseType === 1) {
        if (!this.counselorInfo) {
          this.msgError("请选择顾问");
          return;
        }
      }
      if (this.chooseType === 2) {
        if (!this.salespersonInfo) {
          this.msgError("请选择推广员");
          return;
        }
      }
      this.queryParams.userName = "";
      this.openChooseAdvisor = false;
    },
    cancelChooseAdvisor() {
      if (this.chooseType === 1) {
        this.counselorInfo = null;
      } else {
        this.salespersonInfo = null;
      }
      this.queryParams.userName = "";
      this.openChooseAdvisor = false;
      this.$refs.singleTable.setCurrentRow(null);
    },
    getUserList() {
      this.loading = true;
      listUser({
        ...this.queryParams,
        userType: 2
      }).then(response => {
        this.advisorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询顾问列表 */
    getAdvisorList() {
      this.loading = true;
      listAdvisor(this.queryParams).then(response => {
        this.advisorList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getEditInfo() {
      const { id, type } = this.$route.query;
      if (id) {
        getUser(id).then(response => {
          const data = response.data;
          this.form = {
            ...data,
            birthday: new Date(data.birthday)
          };
          this.counselorInfo = {
            id: data.counselor,
            counselorName: data.counselorName
          };
          this.salespersonInfo = {
            id: data.salesperson,
            salespersonName: data.salespersonName
          };
        });
        this.title = type == 1 ? "用户详情" : "修改用户";
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != null) {
            const data = {
              ...this.form,
              birthday: this.filterDate(this.form.birthday, "YYYY-MM-DD")
            };
            console.log(data);
            updateUser(data).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.$router.go(-1);
              }
            });
          } else {
            const data = {
              ...this.form,
              birthday: this.filterDate(this.form.birthday, "YYYY-MM-DD")
            };
            addUser(data).then(response => {
              if (response.code === 200) {
                this.msgSuccess("添加成功");
                this.$router.go(-1);
              }
            });
          }
        }
      });
    },

    // 重置按钮
    cancel() {
      this.getEditInfo();
      this.resetForm("form");
    },
    removeDevice(index, id) {
      this.form.equipments.splice(index, 1);
      this.form.removeEquipmentIds.push(id);
    }
  }
};
</script>
